package com.ruoyi.wb.service.impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.wb.domain.WbMaintainCompanyUser;
import com.ruoyi.wb.domain.WbMasterEnter;
import com.ruoyi.wb.enmus.RoleNameEnums;
import com.ruoyi.wb.enmus.WbAuditType;
import com.ruoyi.wb.mapper.WbMaintainCompanyUserMapper;
import com.ruoyi.wb.mapper.WbMasterEnterMapper;
import com.ruoyi.wb.service.IWbMaintainCompanyUserService;
import com.ruoyi.wb.service.IWbMasterEnterService;
import com.ruoyi.wb.vo.AcquiringMasterVo;
import com.ruoyi.wb.vo.WbMaintainCompanyUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 师傅入驻Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-10-14
 */
@Service
public class WbMasterEnterServiceImpl implements IWbMasterEnterService 
{
    @Autowired
    private WbMasterEnterMapper wbMasterEnterMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private RedisCache redisCache;


   @Autowired
    private IWbMaintainCompanyUserService wbMaintainCompanyUserService;



 @Autowired
    private WbMaintainCompanyUserMapper wbMaintainCompanyUserMapper;








    /**
     * 查询师傅入驻
     * 
     * @param id 师傅入驻主键
     * @return 师傅入驻
     */
    @Override
    public WbMasterEnter selectWbMasterEnterById(Long id)
    {
        return wbMasterEnterMapper.selectWbMasterEnterById(id);
    }

    /**
     * 查询师傅入驻
     *
     * @param userId 师傅id
     * @return 师傅入驻
     */
    @Override
    public WbMasterEnter selectWbMasterEnterByUserId(Long userId) {

        return wbMasterEnterMapper.selectWbMasterEnterByUserId(userId);
    }

    /**
     * 查询师傅入驻列表
     * 
     * @param wbMasterEnter 师傅入驻
     * @return 师傅入驻
     */
    @Override
    public List<WbMasterEnter> selectWbMasterEnterList(WbMasterEnter wbMasterEnter)
    {
        //如果是维保公司管理员

        return wbMasterEnterMapper.selectWbMasterEnterList(wbMasterEnter);
    }

    /**
     * 新增师傅入驻
     * 
     * @param wbMasterEnter 师傅入驻
     * @return 结果
     */
    @Override
    public int insertWbMasterEnter(WbMasterEnter wbMasterEnter)
    {
        Long userId = SecurityUtils.getUserId();
        //先查询是否已经入驻

        WbMasterEnter wbMasterEnter1 = new WbMasterEnter();
        wbMasterEnter1.setUserId(userId);
        List<WbMasterEnter> wbMasterEnters = wbMasterEnterMapper.selectWbMasterEnterList(wbMasterEnter1);
        long count = wbMasterEnters.stream().filter(item -> !item.getAuditType().equals(WbAuditType.NOTSETTLED.getCode())).count();

        if (count>0){
            throw new RuntimeException("已经入驻无法再次入驻");
        }

        wbMasterEnter.setAuditType(WbAuditType.ALREADYENTERED.getCode());
        wbMasterEnter.setUserId(userId);
        wbMasterEnter.setCreateBy(userId.toString());
        wbMasterEnter.setCreateTime(DateUtils.getNowDate());
        wbMasterEnter.setUpdateBy(userId.toString());
        wbMasterEnter.setUpdateTime(DateUtils.getNowDate());
        return wbMasterEnterMapper.insertWbMasterEnter(wbMasterEnter);
    }

    /**
     * 修改师傅入驻
     * 
     * @param wbMasterEnter 师傅入驻
     * @return 结果
     */
    @Override
    public int updateWbMasterEnter(WbMasterEnter wbMasterEnter)
    {
        Date nowDate = DateUtils.getNowDate();
        SysUser user = SecurityUtils.getLoginUser().getUser();
//        wbMasterEnter.setAuditorName(user.getNickName());
//        wbMasterEnter.setAuditTime(nowDate);
//        wbMasterEnter.setAuditorId(user.getUserId());
        wbMasterEnter.setUpdateTime(nowDate);


        return wbMasterEnterMapper.updateWbMasterEnter(wbMasterEnter);
    }

    /**
     * 批量删除师傅入驻
     * 
     * @param ids 需要删除的师傅入驻主键
     * @return 结果
     */
    @Override
    public int deleteWbMasterEnterByIds(Long[] ids)
    {
        return wbMasterEnterMapper.deleteWbMasterEnterByIds(ids);
    }

    /**
     * 删除师傅入驻信息
     * 
     * @param id 师傅入驻主键
     * @return 结果
     */
    @Override
    public int deleteWbMasterEnterById(Long id)
    {
        return wbMasterEnterMapper.deleteWbMasterEnterById(id);
    }

    /**
     * 审核师傅入驻
     *
     * @param id 师傅入驻主键
     * @return 结果
     */
    @Override
    @Transactional
    public int auditWbMasterEnter(Long id) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getUser();
        WbMasterEnter wbMasterEnter1 = wbMasterEnterMapper.selectWbMasterEnterById(id);
        WbMasterEnter wbMasterEnter = new WbMasterEnter();
        wbMasterEnter.setId(id);
        wbMasterEnter.setAuditorId(sysUser.getUserId());
        wbMasterEnter.setAuditorName(sysUser.getNickName());
        wbMasterEnter.setAuditTime(DateUtils.getNowDate());
        wbMasterEnter.setAuditType(WbAuditType.BEENTERING.getCode());
        //给个角色
        List<SysUserRole> sysUserRoles= new ArrayList<>();
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setRoleId(RoleNameEnums.REPAIR_MAN.getType().longValue());
        sysUserRole.setUserId(wbMasterEnter1.getUserId());
        sysUserRoles.add(sysUserRole);
        List<Long> collect = sysUserRoles.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
        //删除角色失败
        sysUserRoleMapper.delete(wbMasterEnter1.getUserId(),collect);
        //添加角色
        int i = sysUserRoleMapper.batchUserRole(sysUserRoles);
        //弹窗提示
        if(!ObjectUtils.isEmpty(wbMasterEnter.getAuditType())&&wbMasterEnter.getAuditType().equals(WbAuditType.BEENTERING.getCode())){
            wbMasterEnter.setCauseOfRejection("您的师傅入驻申请已经通过,请保持手机畅通。");
            wbMasterEnter.setIfRead(1L);
        }
        //修改师傅入驻
        int j = wbMasterEnterMapper.updateWbMasterEnter(wbMasterEnter);

        //----------------------更新redis缓存信息------------------------
        SysUser itemUser = sysUserMapper.selectUserById(wbMasterEnter1.getUserId());
        if (StringUtils.isNotEmpty(itemUser.getToken())&&redisCache.hasKey(itemUser.getToken())){
            LoginUser itemLoginUser = redisCache.getCacheObject(itemUser.getToken());
            itemLoginUser.setUser(itemUser);
            redisCache.refreshToken(itemUser.getToken(),itemLoginUser);
        }

        return  j;
    }

    @Override
    public WbMasterEnter byUser() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        return  wbMasterEnterMapper.byUser(loginUser.getUserId());

    }

    @Override
    public AjaxResult acquiringMaster() {
        SysUser user = SecurityUtils.getLoginUser().getUser();

       List<AcquiringMasterVo> acquiringMasterVos = new ArrayList<>();

        //外部维修师傅
        List<SysRole> roles = user.getRoles();
        for (SysRole role : roles) {
            if (role.getRoleName().equals(RoleNameEnums.ADMIN.getDescribe())||role.getRoleName().equals(RoleNameEnums.PTGLY.getDescribe())) {//超级管理员
                WbMasterEnter wbMasterEnter = new WbMasterEnter();
                wbMasterEnter.setAuditType(WbAuditType.BEENTERING.getCode());
                List<WbMasterEnter> wbMasterEnters = wbMasterEnterMapper.selectWbMasterEnterList(wbMasterEnter);
                for (WbMasterEnter masterEnter : wbMasterEnters) {
                    AcquiringMasterVo acquiringMasterVo = new AcquiringMasterVo();
                    acquiringMasterVo.setUserId(masterEnter.getUserId());
                    acquiringMasterVo.setUserName(masterEnter.getName());
                    acquiringMasterVos.add(acquiringMasterVo);

                }

                return AjaxResult.success(acquiringMasterVos);
            }
        }


        //内部维修师傅
        RoleNameEnums[] values = RoleNameEnums.values();
        List<String> roleIds = new ArrayList<>();
        for (RoleNameEnums value : values) {
            if (value.isIfWbRole()){
                roleIds.add(value.getType().toString());
            }
        }
        if (CollectionUtils.isEmpty(roleIds)){
            return AjaxResult.success();
        }
        WbMaintainCompanyUser wbMaintainCompanyUser = new WbMaintainCompanyUser();
        wbMaintainCompanyUser.setUserId(user.getUserId());

        List<WbMaintainCompanyUser> wbMaintainCompanyUsers = wbMaintainCompanyUserMapper.selectWbMaintainCompanyUserList(wbMaintainCompanyUser);

        if (!CollectionUtils.isEmpty(wbMaintainCompanyUsers)){
            List<WbMaintainCompanyUserVo> wbMaintainCompanyUserVos = wbMaintainCompanyUserMapper.listWbMaster(roleIds, wbMaintainCompanyUsers.get(0).getMaintainCompanyId());
            for (WbMaintainCompanyUserVo wbMaintainCompanyUserVo : wbMaintainCompanyUserVos) {
                AcquiringMasterVo acquiringMasterVo = new AcquiringMasterVo();
                acquiringMasterVo.setUserId(wbMaintainCompanyUserVo.getUserId());
                acquiringMasterVo.setUserName(wbMaintainCompanyUserVo.getNickName());
                acquiringMasterVos.add(acquiringMasterVo);
            }


            return  AjaxResult.success(acquiringMasterVos);
        }
        return  AjaxResult.success();
    }


}
